<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>SmartLock</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0" />
</head>

<body>
    <div id="title">SmartLock</div>
        <div id="message">已准备好开锁，请操作...</div>

        &copy; SmartLock for kai v1.0 by cgluWxh.
    </div>

    <script src="crypto.js"></script>
    <script>
        const $=(e)=>document.querySelector(e);
        function log(e) {
            $("#message").innerHTML=e;
        }
        const cmdFactory = {
            decodeRes(buffer) {
                let binary = ''
                const bytes = buffer
                const len = bytes.byteLength
                for (let i = 0; i < len; i++) {
                    binary += String.fromCharCode(bytes.getUint8(i))
                }
                return binary;
            },
            md5s(str) {
                return CryptoJS.MD5(str).toString().slice(8, 24);
            },
            aes(str) {
                let key = CryptoJS.enc.Utf8.parse("Fx4k6AWivOsLE4NI");
                let plainText = str;
                let encryptedData = CryptoJS.AES.encrypt(plainText, key, {
                    mode: CryptoJS.mode.ECB,
                    padding: CryptoJS.pad.ZeroPadding
                }).ciphertext;
                let binary_string = atob(CryptoJS.enc.Base64.stringify(encryptedData));
                let len = binary_string.length;
                let bytes = new Uint8Array(len);
                for (let i = 0; i < len; i++) {
                    bytes[i] = binary_string.charCodeAt(i);
                }
                return bytes.buffer;
            },
            genCmdOri(psw, cmd) {
                return (new Date().getTime() / 1000).toFixed(0) + this.md5s(psw) + cmd;
            },
            genCmd(psw, cmd) {
                let ori = this.genCmdOri(psw, cmd);
                return this.aes(ori);
            }
        }
        
        function caul() {
            const adp=navigator.mozBluetooth.defaultAdapter;
            adp.startLeScan(["6e400001-b5a3-f393-e0a9-e50e24dcca9e"])
                .then(discoveryHdr=>{
                    log("开始扫描设备...")
                    discoveryHdr.ondevicefound=(evt)=>{
                        const device=evt.device;
                        if(device.name.indexOf("YILA")==-1)return;
                        log("已扫描到智能锁... 正在连接...")
                        const battery=new Uint8Array(evt.scanRecord).getUint8(20);
                        const server=device.gatt;
                        server.connect().then(()=>{
                            log("已连接上，正在搜寻服务...")
                            for(sid in server.services) {
                                const service=server.services[sid];
                                if (service.uuid === "6e400001-b5a3-f393-e0a9-e50e24dcca9e") {
                                    log("正在搜寻属性...")
                                    for(cid in service.characteristics) {
                                        const chara=service.characteristics[cid];
                                        if (chara.uuid === "6e400002-b5a3-f393-e0a9-e50e24dcca9e") {
                                            chara.writeValue(cmdFactory.genCmd("B482f", `A:OPEN;P:+1800,2000,650;`))
                                                .then(()=>{
                                                    log(`开锁成功！电量${battery}`)
                                                    server.disconnect();
                                                })
                                        }
                                    }

                                }
                            }
                        })
                    }
                })
        }
    </script>
</body>

</html>